package com.chenwy.example.controller;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import java.io.*;

@RestController
@RequestMapping("xml2json")
public class Xml2JsonController {

    /**
     * 依赖
     * 	<dependency>
     * 			<groupId>org.json</groupId>
     * 			<artifactId>json</artifactId>
     * 			<version>20180813</version>
     * 		</dependency>
     * @return
     */
    @RequestMapping(value="jsonJava",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeferredResult jsonJava(){
        DeferredResult deferredResult = new DeferredResult();
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/files/qq.xml");
            String string = new String(IOUtils.toByteArray(inputStream),"gb2312");
            string  = new String(string.getBytes("utf-8"),"utf-8");
            JSONObject jsonObject = XML.toJSONObject(string);
            String result = jsonObject.toString();
            deferredResult.setResult(result);
            System.out.println(System.getProperty("file.encoding"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return deferredResult;
    }

    /**
     * 依赖
     * 	<dependency>
     * 			<groupId>net.sf.json-lib</groupId>
     * 			<artifactId>json-lib</artifactId>
     * 			<version>2.4</version>
     * 			<classifier>jdk15</classifier>
     * 		</dependency>
     * 		<dependency>
     * 			<groupId>xom</groupId>
     * 			<artifactId>xom</artifactId>
     * 			<version>1.2.5</version>
     * 		</dependency>
     * @return
     */
    @RequestMapping(value="jsonLib",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeferredResult jsonLib(){
        DeferredResult deferredResult = new DeferredResult();
        long start  = System.currentTimeMillis();
        XMLSerializer serializer = new XMLSerializer();
        String result = serializer.readFromStream(this.getClass().getResourceAsStream("/files/qq.xml")).toString();
        long end = System.currentTimeMillis();
        System.out.println(String.format("转换耗时：%dms" , end - start));
        deferredResult.setResult(result);
        return deferredResult;
    }
}
